package com.bwc.codevideo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bwc.codevideo.http.AdditionalMessage
import com.bwc.codevideo.http.ApiClient
import com.bwc.codevideo.http.ChatRequest
import com.bwc.codevideo.speak.SpeakAdapter
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import java.io.BufferedReader
import java.io.InputStreamReader

class ChattingActivity : AppCompatActivity() {
    private lateinit var speedAdapter: SpeakAdapter
    private var recycler : RecyclerView?= null

    private var input : EditText ?= null
    private var shuru  : String ?= null

    private var chatting_send : Button ?= null
    private var conversationId : String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.chatting_activitys)
        recycler = findViewById(R.id.chatting_recyc)
        input = findViewById(R.id.chatting_input_Text)
        chatting_send = findViewById(R.id.chatting_send)
        speedAdapter = SpeakAdapter(mutableListOf())
        recycler?.adapter = speedAdapter
        recycler?.layoutManager = LinearLayoutManager(this)
        speedAdapter.addItem("您好，我是您的ai助手，我会为您制定计划哦，请告诉我您的身高体重等信息！")
        input?.addTextChangedListener{text ->
            shuru = text.toString()
        }
        initData()
    }


    private fun initData(){
        chatting_send?.setOnClickListener {
            if (shuru != null){
                speedAdapter.addItem(shuru!!)
                sendChatRequest(shuru!!)
            }
        }



    }

    private fun sendChatRequest(wenti : String) {
        val additionalMessages = listOf(
            AdditionalMessage(
                content = wenti,
                content_type = "text",
                role = "user",
                type = "question"
            )
        )

        val chatRequest = ChatRequest(
            bot_id = "7566466192694181938",
            user_id = "123456789",
            stream = true,
            additional_messages = additionalMessages
        )

        ApiClient.apiService.sendMessage(conversationId,chatRequest).enqueue(object : retrofit2.Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: retrofit2.Response<ResponseBody>) {
                if (response.isSuccessful) {
                    val inputStream = response.body()?.byteStream()
                    val bufferedReader = BufferedReader(InputStreamReader(inputStream))

                    var line: String?
                    speedAdapter.addItem("")
                    var neirong = ""
                    // 逐行读取响应流
                    while (bufferedReader.readLine().also { line = it } != null) {
                        // 使用正则表达式提取 data 部分
                        val eventMatch = Regex("""event:\s*(\S+)""").find(line!!)
                        val dataMatch = Regex("""data:\s*(\{.*\})""").find(line!!)

                        // 如果找到了 data 部分，则提取并解析
                        if (dataMatch != null) {


                            val dataJson = dataMatch.groupValues[1]  // 提取 data 部分的 JSON 字符串

                            try {
                                val jsonData = JSONObject(dataJson)  // 将 data 字符串解析为 JSON 对象

                                // 你可以根据需求提取字段
                                val id = jsonData.optString("id", "未知ID")
                                val conversationIds = jsonData.optString("conversation_id", "未知对话ID")
                                val content = jsonData.optString("content", " ")
                                conversationId = conversationIds
                                // 打印或进一步处理 data
                                println("ID: $id")
                                println("Conversation ID: $conversationIds")
                                println("Content: $content")
                                neirong += content
                                runOnUiThread{
                                    speedAdapter.updateItem(speedAdapter.itemCount -1,neirong)
                                }
                                input?.text = null


                            } catch (e: Exception) {
                                println("解析 data 字段时出错: ${e.message}")
                            }
                        }
                    }

                    bufferedReader.close()

                } else {
                    Log.e("TAG", "Error: ${response.message()}")
                }

            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                t.printStackTrace()
            }
        })
    }


}